package org.deng.learn.zookeeper;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;

/**
 * @Author DengLibin
 * @Date 19-5-12
 * @Time 下午4:11
 * @Desc zookeeper操作api
 */
public class ApiDemo {

    //服务器集群
    private static String servers = "node2:2181,node3:2181,node4:2181";
    //客户端
    private static  ZooKeeper client;

    /**
     * 创建客户端 并连接服务器
     * @throws IOException
     */
    private  static  void initClient() throws IOException {
        client = new ZooKeeper(servers, 2 * 1000, event -> {
            System.out.println("有监听事件: path:"+event.getPath()+" \ntype:"+event.getType().name());
        });
    }

    /**
     * 创建节点
     */
    private  static  void createNode(String path, String data) throws KeeperException, InterruptedException {
        System.out.println("创建节点:"+path);
        String pathResult = client.create(path, data.getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);//创建模式 永久
        System.out.println("创建节点结果:"+pathResult);

    }

    /**
     * 获取子节点并监控子节点的变化(删除和创建)
     */
    private static  void getChildrenAndWatch(String path) throws KeeperException, InterruptedException {
        List<String> children = client.getChildren(path, true);
        System.out.println(path +"的子节点:");
        for(String child : children){
            System.out.println(child);
        }
    }

    /**
     * 删除节点
     * @param path
     * @throws KeeperException
     * @throws InterruptedException
     */
    private static  void deleteNode(String path) throws KeeperException, InterruptedException {
        client.delete(path, 0);
    }

    /**
     * 节点是否存在
     * @param path
     * @throws KeeperException
     * @throws InterruptedException
     */
    private static  void isExist(String path) throws KeeperException, InterruptedException {
        Stat stat = client.exists(path, true);

        System.out.println("节点是否存在:"+ (stat != null));

    }

    public static  void main(String[] args) throws IOException, KeeperException, InterruptedException {
         initClient();

         getChildrenAndWatch("/denglibin");

        // createNode("/denglibin/child1", "child1 msg");

       // deleteNode("/denglibin/child1");
        isExist("/denglibin/child");

    }
}
